import shutil
import os
from datetime import datetime

class BackupManager:
    def __init__(self, target_file):
        self.target_file = target_file
        self.backup_dir = "/var/backups/grub-editor"

    def create_backup(self):
        if not os.path.exists(self.backup_dir):
            os.makedirs(self.backup_dir)
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_path = os.path.join(self.backup_dir, f"grub.cfg.{timestamp}")
        shutil.copy2(self.target_file, backup_path)

    def restore_backup(self):
        backups = sorted(
            [f for f in os.listdir(self.backup_dir) if f.startswith("grub.cfg.")],
            reverse=True
        )
        if not backups:
            return False

        latest = os.path.join(self.backup_dir, backups[0])
        try:
            shutil.copy2(latest, self.target_file)
            return True
        except Exception as e:
            print("恢复备份失败:", e)
            return False